package com.sdonkey.score.filter;


import org.apache.log4j.Logger;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 强制登录过滤器
 *
 * @author ZhaoShihao
 * @version 1.0
 */
@WebFilter(urlPatterns = "/*")
public class MustLogin implements Filter {
    Logger logger=Logger.getLogger(MustLogin.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        String uri = request.getRequestURI();
        //判断需要拦截的路径
        if (uri.contains(".html") || uri.contains("/ajax")) {
            //判断需要放行的路径
            if (!uri.contains("/register") && !uri.contains(request.getContextPath() + "/ajax")
                    && !uri.contains("/retrievePassword") && !uri.contains("/login") && !uri.contains("/error.html")) {
                //判断session中是否存在用户
                HttpSession session = request.getSession(true);
                Object user = session.getAttribute("user");
                Object id = session.getAttribute("id");
                if (user == null || id == null) {
                    clearCookie(request, response);
                    //重定向到登录页面
                    response.sendRedirect(request.getContextPath());
                    return;
                }
            }
        }
        //放行
        filterChain.doFilter(servletRequest, servletResponse);
    }

    @Override
    public void destroy() {

    }

    /**
     * 清空cookie
     */
    private void clearCookie(HttpServletRequest request, HttpServletResponse response) {
        Cookie[] cookies = request.getCookies();
        try {
            for (Cookie cooky : cookies) {
                if (!cooky.getName().equals("remember")&&!cooky.getName().equals("JSESSIONID")) {
                    Cookie cookie = new Cookie(cooky.getName(), null);
                    cookie.setMaxAge(0);
                    cookie.setPath(request.getContextPath());//根据你创建cookie的路径进行填写
                    response.addCookie(cookie);
                }
            }
        } catch (Exception ex) {
            System.out.println("清空Cookies发生异常！");
        }
    }
}
